package org.dromara.gateway.listener;

import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.client.naming.event.InstancesChangeEvent;
import com.alibaba.nacos.common.notify.NotifyCenter;
import com.alibaba.nacos.common.notify.listener.Subscriber;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cloud.loadbalancer.core.CachingServiceInstanceListSupplier;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public  class NacosInstancesChangeEventListener extends Subscriber<InstancesChangeEvent> {

    private static final Logger log = LoggerFactory.getLogger(NacosInstancesChangeEventListener.class);

    private final Map<String, List<Instance>> hostMap = new HashMap<>();

    @Resource
    private CacheManager defaultLoadBalancerCacheManager;

    @PostConstruct
    public void init() {
        // 注册当前自定义的订阅者以获取通知
        NotifyCenter.registerSubscriber(this);
    }

    @Override
    public void onEvent(InstancesChangeEvent event) {
        String serviceName = event.getServiceName();
        // serviceName 格式为 groupName@@name
        String split = Constants.SERVICE_INFO_SPLITER;
        if (serviceName.contains(split)) {
            serviceName = serviceName.substring(serviceName.indexOf(split) + split.length());
        }
//        log.info("服务上下线: {}", serviceName);

        List<Instance> oldhosts = hostMap.get(serviceName);

        List<Instance> hosts = event.getHosts();

        if ((oldhosts == null && !hosts.isEmpty()) || (oldhosts != null && oldhosts.size() < hosts.size())) {
            log.info("{}  服务上线", serviceName);
        } else {
            log.info("{}  服务下线", serviceName);
        }
        hostMap.put(serviceName, hosts);

        Cache cache = defaultLoadBalancerCacheManager.getCache(CachingServiceInstanceListSupplier.SERVICE_INSTANCE_CACHE_NAME);
        if (cache != null) {
            cache.evict(event.getServiceName());
        }
        log.info("缓存刷新完成");
    }

    @Override
    public Class<? extends com.alibaba.nacos.common.notify.Event> subscribeType() {
        return InstancesChangeEvent.class;
    }
}
